/**
* @Title: SupportBasicStaticPage.java
* @Package com.yly.module.system.staticpage
* @Description: TODO
* @author zz
* @date 2013-12-21 下午2:09:12
* @version V1.0
*/
package com.yly.utils.staticpage;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import com.yly.constant.Constant;
import com.yly.utils.IOUtil;
import com.yly.utils.StrUtil;

import freemarker.core.Environment;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * @ClassName: SupportBasicStaticPage
 * @Description: TODO
 * @author zz
 * @date 2013-12-21 下午2:09:12
 */
public class SupportBasicStaticPage {
	
	
	/**
	 * <p>Title: 生成静态页面</p>
	 * <p>Description: 生成静态页面</p>
	 * @param templatePathAndName 模板位置
	 * @param tagNameAndName 生成位置
	 * @param dataMap 数据对象
	 * @throws TemplateException
	 * @throws IOException
	 */
	@SuppressWarnings("rawtypes")
	public static void createStaticPage(String templatePathAndName, String tagPathAndName, Map dataMap) throws IOException, TemplateException{
		
		createStaticPage(templatePathAndName, tagPathAndName, dataMap, null);
	}
	
	/**
	 * <p>Title: 生成静态页面</p>
	 * <p>Description: 生成静态页面</p>
	 * @param templatePathAndName 模板位置
	 * @param tagNameAndName 生成位置
	 * @param dataMap 数据对象
	 * @param encoding 编码格式
	 * @throws TemplateException
	 * @throws IOException
	 */
	@SuppressWarnings("rawtypes")
	public static void createStaticPage(String templatePathAndName, String tagPathAndName, Map dataMap, String encoding) throws TemplateException, IOException{
		
		Template template = null;
		
		try {
			
			template = ConfigurationFactory.getConfiguration().getTemplate(templatePathAndName);
			
		} catch (IOException e) {
			
			e.printStackTrace();
			
			throw e;
			
		} 
		
		File htmlFile = IOUtil.getFolderAndFile(Constant.SP_TARGET_PATH + tagPathAndName);
		
		Writer out = null;
		
		try {
			
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), encoding));
			
			if(!StrUtil.nil(encoding)){
				
				Environment env =  template.createProcessingEnvironment(dataMap, out); 
				
				env.setOutputEncoding(encoding); 
				
				env.process(); 
				
			}else{
				
				template.process(dataMap, out);
			}
			
		} catch (IOException e) {
			
			e.printStackTrace();
			
		} finally{
			
			try {
				if(out != null){
					out.flush();
					out.close();
				}
			} catch (IOException e) {
				
				e.printStackTrace();
			}
			
		}
		
	}
	
	
	
	
}
